﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Text;
using System.Xml.Linq;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.SharePoint;
using Microsoft.VisualStudio.SharePoint.Explorer;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.SharePoint.Explorer.Extensions;
using SPVSX.Explorer.Extensions.NodeInformation;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using SPVSX.Explorer.Extensions.CommandIds;

namespace SPVSX.Explorer.Extensions
{
    /// <summary>
    /// Extend the site node for Content Type with functionality
    /// </summary>
    [Export(typeof(IExplorerNodeTypeExtension))]
    //The node type to bind with
    [ExplorerNodeType(ExtensionNodeTypes.ContentTypeNode)]
    class ContentTypeNodeExtension : IExplorerNodeTypeExtension
    {
        #region Methods

        public void Initialize(IExplorerNodeType nodeType)
        {
            nodeType.NodeMenuItemsRequested += new EventHandler<ExplorerNodeMenuItemsRequestedEventArgs>(nodeType_NodeMenuItemsRequested);
        }

        void nodeType_NodeMenuItemsRequested(object sender, ExplorerNodeMenuItemsRequestedEventArgs e)
        {
            

            IMenuItem item = e.MenuItems.Add("Import Content Type");
            item.Click += new EventHandler<MenuItemEventArgs>(item_Click);
           
            IContentTypeNodeInfo annotation = e.Node.GetAnnotation<IContentTypeNodeInfo>();
            //item.IsEnabled = SharePointCommands.IsPublishingContentType(e.Node, annotation.Name);

        }

        void item_Click(object sender, MenuItemEventArgs e)
        {
            IExplorerNode owner = (IExplorerNode)e.Owner;
            IContentTypeNodeInfo annotation = owner.GetAnnotation<IContentTypeNodeInfo>();
            if (owner.Context.SharePointConnection.ExecuteCommand<string, bool>(ContentTypeCommandIds.IsBuiltInContentType, annotation.Name))
            {
                if (MessageBox.Show("This is a built in Content Type, do you still want to import it?", "Import built in Content Type", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    ImportContentType(e);
                }
            }
            else
            {
                ImportContentType(e);
            }
        }

        void ImportContentType(MenuItemEventArgs e)
        {
            IExplorerNode owner = (IExplorerNode)e.Owner;
            IContentTypeNodeInfo annotation = owner.GetAnnotation<IContentTypeNodeInfo>();
            ContentTypeNodeInfo contentTypeInfo =
            owner.Context.SharePointConnection.ExecuteCommand<string, ContentTypeNodeInfo>(ContentTypeCommandIds.GetContentTypeImportProperties, annotation.Name);

            if (contentTypeInfo != null)
            {
                //Create the encoding definition
                XDeclaration declaration = new XDeclaration("1.0", Encoding.UTF8.WebName, null);

                XNamespace sharepointToolsNamespace = @"http://schemas.microsoft.com/VisualStudio/2010/SharePointTools/SharePointProjectItemModel";
                XNamespace sharepointNamespace = @"http://schemas.microsoft.com/sharepoint/";

                #region spdata

                XElement projectItemFile1 = new XElement("ProjectItemFile",
                    new XAttribute("Source", "Elements.xml"),
                    new XAttribute("Target", @"ContentType1\"),
                    new XAttribute("Type", "ElementManifest"));

                XElement files1 = new XElement(XNamespace.None + "Files", projectItemFile1);


                XElement projectItem4 = new XElement(sharepointToolsNamespace + "ProjectItem",
                    new XAttribute("Type", "Microsoft.VisualStudio.SharePoint.ContentType"),
                    new XAttribute("DefaultFile", "Elements.xml"),
                    new XAttribute("SupportedTrustLevels", "All"),
                    new XAttribute("SupportedDeploymentScopes", "Web, Site"),
                    files1);


                string wes = projectItem4.ToString();
                XDocument doc1 = new XDocument(declaration, projectItem4);

                string miffy = doc1.ToString();

                string xr = miffy.Replace(@" xmlns=""""", "");

                xr = doc1.Declaration.ToString() + xr;

                #endregion

                #region elements

                XElement elements = new XElement(sharepointNamespace + "Elements");

                elements.Add(XElement.Parse(contentTypeInfo.ToString()));

                string elementsAsString = elements.ToString().Replace(@" xmlns=""""", "");

                XDocument elementsDoc = new XDocument(declaration, elements);

                string elem = elementsDoc.ToString();

                string finalElements = elem.Replace(" xmlns=\"\"", "");


                #endregion

                DTE2 globalService = Package.GetGlobalService(typeof(SDTE)) as DTE2;

                Project project = null;
                Array activeSolutionProjects = globalService.DTE.ActiveSolutionProjects as Array;
                if ((activeSolutionProjects != null) && (activeSolutionProjects.Length > 0))
                {
                    project = activeSolutionProjects.GetValue(0) as Project;
                }

                string tempFolderName = Path.GetRandomFileName();

                ProjectItem folder = project.ProjectItems.AddFolder(tempFolderName, "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}");

                string tempElementsFileName = Path.GetTempFileName();
                using (StreamWriter writer = new StreamWriter(tempElementsFileName, false))
                {
                    writer.WriteLine(finalElements);
                }

                ProjectItem elementsProjectItem = folder.ProjectItems.AddFromTemplate(tempElementsFileName, "Elements.xml");

                if (elementsProjectItem != null)
                {
                    Window window = elementsProjectItem.Open("{00000000-0000-0000-0000-000000000000}");
                    window.Visible = true;
                    window.Activate();                   
                }

                File.Delete(tempElementsFileName);

                string tempSPDataFileName = Path.GetTempFileName();
                using (StreamWriter writer2 = new StreamWriter(tempSPDataFileName, false))
                {
                    writer2.WriteLine(xr);
                }
                ProjectItem spDataProjectItem = folder.ProjectItems.AddFromTemplate(tempSPDataFileName, "SharePointProjectItem.spdata");

                File.Delete(tempSPDataFileName);

                folder.Name = annotation.Name;
            }
        }

        #endregion
    }
}
